#include "qlinemesh.h"
QLineMesh::QLineMesh(QVector<QVector3D>& vertices, QVector<unsigned int>& indices, Qt3DCore::QNode* root, PrimitiveType primitiveType)
	: QGeometryRenderer(root)
{
	// 构造QGeometry
	geometry = new Qt3DRender::QGeometry(root);
	// 构造顶点数组
	QByteArray bufferBytes;
    bufferBytes.resize(3 * vertices.size() * sizeof(float));
    auto *positions = reinterpret_cast<float*>(bufferBytes.data());
	for (int n = vertices.size(), i = 0; i < n; ++i)
	{
		*positions++ = vertices[i].x();
		*positions++ = vertices[i].y();
		*positions++ = vertices[i].z();
	}
    m_vertexBuffer = new Qt3DRender::QBuffer(geometry);
    m_vertexBuffer->setData(bufferBytes);
	// 设置位置属性
    m_positionAttribute = new Qt3DRender::QAttribute(geometry);
    m_positionAttribute->setName(Qt3DRender::QAttribute::defaultPositionAttributeName());
	// 数据类型
    m_positionAttribute->setVertexBaseType(Qt3DRender::QAttribute::Float);
	// Holds the data size, it can only be 1 to 4 units (scalars and vectors),
	// 9 units (3x3 matrices) or 16 units (4x4 matrices).
    m_positionAttribute->setVertexSize(3);
    m_positionAttribute->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
    m_positionAttribute->setBuffer(m_vertexBuffer);
	// VertexAttribute: used to define data to be read on a per vertex basis
	// IndexAttribute:  used to define vertex indices when indexed draw calls are to be used
    m_positionAttribute->setByteStride(3 * sizeof(float));
	// 顶点个数
    m_positionAttribute->setCount(vertices.size());
    geometry->addAttribute(m_positionAttribute);
	// 构造索引数组
    QByteArray indexBytes;
	indexBytes.resize(indices.size() * sizeof(unsigned int)); // start to end
	memcpy(indexBytes.data(), indices.data(), indices.size() * sizeof(unsigned int));
    m_indexBuffer = new Qt3DRender::QBuffer(geometry);
    m_indexBuffer->setData(indexBytes);
	// 设置索引属性
	m_indexAttribute = new Qt3DRender::QAttribute(geometry);
	m_indexAttribute->setVertexBaseType(Qt3DRender::QAttribute::UnsignedInt);
	m_indexAttribute->setAttributeType(Qt3DRender::QAttribute::IndexAttribute);
	m_indexAttribute->setVertexSize(1);
	m_indexAttribute->setBuffer(m_indexBuffer);
	m_indexAttribute->setByteStride(1 * sizeof(unsigned int));
	m_indexAttribute->setCount(indices.size());
	geometry->addAttribute(m_indexAttribute);
	// 设置图元
	setPrimitiveType(primitiveType);
	setGeometry(geometry);
}


QLineMesh::~QLineMesh()
{
	delete m_positionAttribute;
	delete m_indexAttribute;
	delete m_vertexBuffer;
	delete m_indexBuffer;
	delete geometry;
}


